import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus, BadRequestException } from '@nestjs/common';
import { Response } from 'express';
import console from './common/console';
import _response from './common/response';

@Catch()
export class ErrorFilter implements ExceptionFilter {
    catch(error: Error, host: ArgumentsHost) {
        let request = host.switchToHttp().getRequest<Request>();
        let response = host.switchToHttp().getResponse<Response>();
        let status = error instanceof HttpException ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        console.error(request.url, error.message, status);
        switch (status) {
            case HttpStatus.NOT_FOUND:
                return response.json(_response.errorNotFound());
            case HttpStatus.UNAUTHORIZED:
                return response.json(_response.errorUnauthorized());
            case HttpStatus.FORBIDDEN:
                return response.json(_response.errorForbidden());
            case HttpStatus.BAD_REQUEST:
                if (error instanceof BadRequestException) {
                    let errorResponse: any = error.getResponse();
                    let _message = errorResponse.message;
                    if (_message instanceof Array) {
                        _message = _message.join(',');
                    }
                    return response.json(_response.error(_message));
                }
            default:
                return response.json(_response.errorServer(error.message));
        }
    }
}
